<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "role".
 *
 * @property string $id
 * @property string $role_name
 * @property string $created_at
 * @property string $updated_at
 * @property integer $is_usable
 */
class Role extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'role';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['created_at', 'updated_at', 'is_usable'], 'integer'],
            [['role_name'], 'string', 'max' => 50],
        ];
    }
    public function attributes()
    {
        return array_merge(parent::attributes(),['pris']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'role_name' => '角色名称',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'is_usable' => '是否可用',
            'pris' => '权限集合',
        ];
    }
    /**
     * 数据保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert))
        {
            if($insert)
            {
                $this->created_at = time();
            }
            //处理权限
            $this->updated_at = time();
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 保存后
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $post = Yii::$app->request->post();
        $pris = $post['Role']['pris'];
        $id = $this->id;
        //生成插入的数组
        $data = [];
        foreach($pris as $v)
        {
            $_data=[];
            $_data[] = 1;
            $_data[] = $id;
            $_data[] = $v;
            $_data[] = time();
            $data[] = $_data;
        }
        if($insert)
        {//新增,

        }
        else
        {//修改
            //先删除对应的权限
            Yii::$app->db->createCommand()->delete('privilegecollect',['type'=>1,'quote_id'=>$id])->execute();

        }
        //增加对应的权限
        Yii::$app->db->createCommand()->batchInsert('privilegecollect', ['type', 'quote_id','pri_id','created_at'], $data)->execute();
    }
}
